/**
 * @Description: 计算器
 * @Author bianpengfei
 * @create 2021/6/25 9:09
 */
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

class Count extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {}
    console.log('初始化', props)
  }

  onAdd = () => {
    this.props.addCount(this.props.count + 1)
  }

  onSub = () => {
    this.props.subCount(this.props.count - 1)
  }

  onAddAsync = () => {
    this.props.addCountAsync(this.props.count)()
  }

  render() {
    const { count } = this.props
    return (
      <div>
        <h1>{count}</h1>
        <button onClick={this.onAdd}>加1</button>
        <button onClick={this.onSub}>减1</button>
        <button onClick={this.onAddAsync}>异步加1</button>
      </div>
    )
  }
}

Count.propTypes = {}

const mapStateToProps = state => {
  return {
    count: state.count
  }
}
const mapDispatchToProps = dispatch => {
  return {
    addCount: count => dispatch({ type: 'increment', payload: count }),
    subCount: count => dispatch({ type: 'subtract', payload: count }),
    addCountAsync: count => {
      return () => {
        setTimeout(() => {
          // Yay! Can invoke sync or async actions with `dispatch`
          console.log(`Yay! Can invoke sync or async actions with \`dispatch\``, count)
          dispatch({ type: 'increment', payload: count + 10 })
        }, 1000)
      }
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Count)
